import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    fruits: [
      { id: 1, name: '苹果', price: 5 },
      { id: 2, name: '香蕉', price: 3 },
      { id: 3, name: '橙子', price: 4 }
    ],
    cart: []
  },
  getters: {
    getFruits: state => state.fruits,
    getCart: state => state.cart
  },
  mutations: {
    addToCart(state, fruit) {
      const existingItem = state.cart.find(item => item.id === fruit.id);
      if (existingItem) {
        existingItem.quantity++;
      } else {
        state.cart.push({ ...fruit, quantity: 1 });
      }
    }
  },
  actions: {
    addToCart({ commit }, fruit) {
      commit('addToCart', fruit);
    }
  },
  modules: {
  }
})